<?php
class Post_model extends CI_Model {

    function __construct() {
        // call the Model constructor
        parent::__construct();
		$this->load->database();
		$this->load->library('session');
    }
    
	function get_next_post() {
		$sql = "SELECT * FROM posts WHERE status = 1 ORDER BY rand() LIMIT 1";
		$query = $this->db->query($sql); 
		$returned = $query->result();
		
		return $returned[0];
	}
	
	function get_post_by_id($id) {
		$sql = "SELECT * FROM posts WHERE id = ?";
		$query = $this->db->query($sql, array($id)); 
		$returned = $query->result();
		
		return $returned[0];
	}	
	
	function rate($post_id, $score) {
		if ($this->session->userdata('user')) { // rate by a registered user
			// check if already rated
			$sql = "SELECT COUNT(*) AS c FROM post_rate WHERE user_id = ? AND post_id = ?"; 
			if ($this->db->query($sql, array($this->session->userdata('user')->id, $post_id))->first_row()->c == 0) {
				$sql = "INSERT INTO post_rate (post_id, user_id, score, date_created, ip) VALUES (?, ?, ?, NOW(), ?)";
				$this->db->query($sql, array($post_id, $this->session->userdata('user')->id, $score, $this->input->ip_address()));
			} else { // already rated, update instead
				$sql = "UPDATE post_rate SET score = ?, date_modified = NOW() WHERE user_id = ? AND post_id = ?";
				$this->db->query($sql, array($score, $this->session->userdata('user')->id, $post_id)); 				
			}
		} else { // rate by a guest
			$sql = "INSERT INTO post_rate (post_id, score, date_created, ip) VALUES (?, ?, NOW(), ?)";
			$this->db->query($sql, array($post_id, $score, $this->input->ip_address()));
		}
	}
	
	function create($filename, $filename_l, $filename_m, $filename_s) {
		$sql = "INSERT INTO posts (img_path_full, img_path_large, img_path_medium, img_path_small, description, status, user_id, ip, date_created) VALUES (?, ?, ?, ?, ?, 0, ?, ?, NOW())";
		$this->db->query($sql, array(
			$filename, 
			$filename_l,
			$filename_m,
			$filename_s,
			$this->input->post('desc'), 
			intval($this->session->userdata('user')->id), 
			$this->input->ip_address()
		));
		return mysql_insert_id();
	}
	
	// for admin control
	function get_unapproved_posts() {
		$sql = "SELECT p.id AS post_id, p.img_path_full, p.img_path_small, p.description, p.ip, u.username FROM posts p JOIN users u ON p.user_id = u.id WHERE p.status = 0 ORDER BY p.date_created DESC";
		$query = $this->db->query($sql); 
		$returned = $query->result();
		return $returned;	
	}

	function approve($id) {
		$sql = "UPDATE posts SET status = 1 WHERE id = ?";
		$this->db->query($sql, array($id)); 
	}

	function disapprove($id) {
		$sql = "UPDATE posts SET status = -1 WHERE id = ?";
		$this->db->query($sql, array($id)); 
	}
}
